const { ref } = Vue;

const states = []; //存储state的容器
const stateSetters = []; //存储修改state方法的容器
let stateIndex = 0; //索引为了让state和方法一一对应

export default function useState(initialState) {
  //创建state到states容器
  states[stateIndex] = createState(initialState, stateIndex);

  //保证stateSetters容器没有值时
  if (!stateSetters[stateIndex]) {
    //容器中新增方法
    stateSetters.push(createStateSetter(stateIndex));
  }

  const _state = states[stateIndex];
  const _setState = stateSetters[stateIndex];

  //每次执行本函数会索引自增
  stateIndex++;

  //返回数据和修改数据的方法
  return [_state, _setState];
}

function createState(initialState, stateIndex) {
  //ref包装state数据
  const state = ref(initialState);
  //有值返回states[stateIndex] 没值返回state 避免覆盖
  return states[stateIndex] !== undefined ? states[stateIndex] : state;
}

function createStateSetter(stateIndex) {
  return function (newState) {
    //写法1 <button @click="setCount(count => count.value + 1)">plus</button>
    //写法2 <button @click="setCount(count - 1)">minus</button>
    if (typeof newState === 'function') {
      //可能是一个函数
      states[stateIndex].value = newState(states[stateIndex]);
    } else {
      //可能是一个表达式
      states[stateIndex].value = newState;
    }
  };
}
